from fastapi import APIRouter, Depends, HTTPException, status
from datetime import date, timedelta
from models.user import User  # Tortoise-ORM的User模型
from models.sign_in import DailySignIn  # Tortoise-ORM的签到模型
from pydantic import BaseModel

router = APIRouter(
    prefix="/api/sign",
    tags=["签到"]
)

# 依赖项：获取当前登录用户（Tortoise-ORM异步版本）
async def get_current_user():
    # 实际项目中应从token解析用户ID（这里简化处理）
    user_id = 1  # 替换为真实的用户ID获取逻辑
    user = await User.filter(id=user_id).first()  # Tortoise查询方式
    if not user:
        raise HTTPException(status_code=401, detail="用户未登录")
    return user

class SignStatusResponse(BaseModel):
    """签到状态响应模型"""
    has_signed: bool
    continuous_days: int
    today: str

@router.get("/status", response_model=SignStatusResponse)
async def get_sign_status(
    current_user: User = Depends(get_current_user)
):
    """获取用户今日签到状态（异步版本）"""
    today = date.today()
    
    # 查询今日是否已签到（Tortoise异步查询）
    sign_record = await DailySignIn.filter(
        user_id=current_user.id,
        sign_date=today
    ).first()
    
    # 计算连续签到天数
    continuous_days = 0
    if sign_record:
        continuous_days = sign_record.continuous_days
    else:
        # 检查昨天是否签到
        yesterday = today - timedelta(days=1)
        yesterday_record = await DailySignIn.filter(
            user_id=current_user.id,
            sign_date=yesterday
        ).first()
        if yesterday_record:
            continuous_days = yesterday_record.continuous_days
    
    return {
        "has_signed": bool(sign_record),
        "continuous_days": continuous_days,
        "today": today.isoformat()
    }

@router.post("/")
async def sign_in(
    current_user: User = Depends(get_current_user)
):
    """用户执行签到（异步版本）"""
    today = date.today()
    
    # 检查是否已签到
    existing_sign = await DailySignIn.filter(
        user_id=current_user.id,
        sign_date=today
    ).first()
    if existing_sign:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="今日已签到，请勿重复签到"
        )
    
    # 计算连续签到天数
    yesterday = today - timedelta(days=1)
    yesterday_record = await DailySignIn.filter(
        user_id=current_user.id,
        sign_date=yesterday
    ).first()
    
    continuous_days = 1
    if yesterday_record:
        continuous_days = yesterday_record.continuous_days + 1
    
    # 创建签到记录（Tortoise保存）
    new_sign = await DailySignIn.create(
        user_id=current_user.id,
        sign_date=today,
        continuous_days=continuous_days,
        points_earned=1  # 基础积分
    )
    
    # 增加积分（处理连续7天额外奖励）
    added_points = 1
    if continuous_days % 7 == 0:
        added_points += 2  # 每7天额外奖励2积分
        new_sign.points_earned = added_points
        await new_sign.save()  # 更新签到记录的积分
    
    # 更新用户总积分（注意：User模型的total_points是CharField，需要转换）
    current_user.total_points = str(int(current_user.total_points or 0) + added_points)
    await current_user.save()  # Tortoise保存用户信息
    
    return {
        "success": True,
        "message": "签到成功",
        "data": {
            "continuous_days": continuous_days,
            "added_points": added_points,
            "total_points": current_user.total_points
        }
    }